import csv
from datetime import datetime, timedelta
import os
import sys


def process_with_basic_reader(csv_file_path, output_file_path):
    """使用Python基础csv模块读取文件，绕过pandas的read_csv问题"""

    # 验证文件存在性和可读性
    if not os.path.exists(csv_file_path):
        print(f"错误：文件不存在 - {csv_file_path}")
        return None

    if not os.access(csv_file_path, os.R_OK):
        print(f"错误：没有文件读取权限 - {csv_file_path}")
        return None

    # 检查路径是否包含中文（可能导致问题）
    if any('\u4e00' <= c <= '\u9fff' for c in csv_file_path):
        print("警告：文件路径包含中文，可能导致读取失败")
        print("建议：将文件移动到纯英文路径，如 D:\\data\\file.csv")

    base_time = datetime(2016, 11, 13, 2, 18, 0)
    activities = []
    headers = None

    try:
        # 使用基础Python csv模块读取
        with open(csv_file_path, 'r', encoding='utf-8', errors='ignore') as f:
            reader = csv.reader(f)

            # 读取表头
            headers = next(reader)
            print(f"检测到表头: {headers}")

            # 查找必要的列索引
            try:
                time_idx = headers.index('time')
                annotation_idx = headers.index('annotation')
                print(f"时间列索引: {time_idx}, 活动列索引: {annotation_idx}")
            except ValueError as e:
                print(f"错误：找不到必要的列 - {e}")
                return None

            # 逐行读取和处理（适合大文件）
            line_count = 0
            for row in reader:
                line_count += 1
                if line_count % 10000 == 0:  # 每处理10000行显示进度
                    print(f"已处理 {line_count} 行...")

                # 跳过空行或不完整的行
                if len(row) <= max(time_idx, annotation_idx):
                    continue

                # 解析时间
                try:
                    time_str = row[time_idx]
                    parts = time_str.split(':')
                    if len(parts) != 2:
                        continue

                    minutes = int(parts[0])
                    sec_msec = parts[1].split('.')
                    seconds = int(sec_msec[0])
                    msec = int(sec_msec[1]) if len(sec_msec) > 1 else 0

                    current_time = base_time + timedelta(
                        minutes=minutes,
                        seconds=seconds,
                        milliseconds=msec
                    )
                except:
                    continue  # 跳过时间解析失败的行

                # 提取活动类型
                try:
                    annotation = row[annotation_idx]
                    act_parts = annotation.split(';')[0].split()
                    activity = act_parts[1].lower() if len(act_parts) >= 2 else 'unknown'
                except:
                    activity = 'unknown'

                activities.append({
                    'datetime': current_time,
                    'activity': activity
                })

        print(f"文件读取完成，共处理 {line_count} 行，有效数据 {len(activities)} 行")

        # 按时间排序
        activities.sort(key=lambda x: x['datetime'])

        # 合并连续相同的活动
        result = []
        current_act = None
        current_start = None
        current_id = 1

        for item in activities:
            if item['activity'] != current_act:
                if current_act is not None:
                    result.append({
                        'id': current_id,
                        'activity': current_act,
                        'start_time': current_start.strftime('%Y.%m.%d %H:%M'),
                        'end_time': prev_time.strftime('%Y.%m.%d %H:%M')
                    })
                current_act = item['activity']
                current_start = item['datetime']
            prev_time = item['datetime']

        # 添加最后一个活动
        if current_act is not None:
            result.append({
                'id': current_id,
                'activity': current_act,
                'start_time': current_start.strftime('%Y.%m.%d %H:%M'),
                'end_time': prev_time.strftime('%Y.%m.%d %H:%M')
            })

        # 保存结果
        with open(output_file_path, 'w', newline='', encoding='utf-8-sig') as f:
            writer = csv.DictWriter(f, fieldnames=['id', 'activity', 'start_time', 'end_time'])
            writer.writeheader()
            writer.writerows(result)

        print(f"结果已保存到: {output_file_path}")
        print("\n结果预览:")
        for row in result[:10]:  # 显示前10行
            print(row)

        return result

    except Exception as e:
        print(f"处理过程中发生错误: {str(e)}")
        return None


if __name__ == "__main__":
    # 请确保路径是纯英文且正确
    input_csv = r"D:\FP\capture24\capture24\P001.csv"  # 替换为你的CSV文件路径
    output_csv = r"D:\FP\capture24\result"  # 输出文件路径

    # 执行处理
    process_with_basic_reader(input_csv, output_csv)